﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RoboServ
{
    class XBeeResponse : XBeeMessage
    {
        public const byte RESP_AT_LOCAL = 0x88;
        public const byte RESP_AT_REMOTE = 0x97;
        public const byte RESP_TX_STATUS = 0x89;
        public const byte RESP_RX_16BIT = 0x80;
        public const byte RESP_RX_64BIT = 0x81;

        public bool checksumFailed;

        public XBeeResponse(byte[] bytes)
        {
            apiID = bytes[0];
            int curByte = 1;

            // RX responses do not have msg (Frame) IDs, everything else does
            if (apiID != RESP_RX_16BIT && apiID != RESP_RX_64BIT)
            {
                msgID = bytes[curByte];
                curByte++;
            }

            if (apiID == RESP_AT_REMOTE || apiID == RESP_RX_64BIT)
            {
                byte[] addr = Utils.getSubArray(bytes, curByte, 8);
                set64BitAddress(Utils.bytesToInt(addr));
                curByte += 8;
            }

            if (apiID == RESP_AT_REMOTE || apiID == RESP_RX_16BIT)
            {
                byte[] addr = Utils.getSubArray(bytes, curByte, 2);
                set16BitAddress((UInt16)Utils.bytesToInt(addr));
                curByte += 2;
            }

            data = new byte[bytes.Length - curByte-1];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = bytes[i + 2];
            }

            checksumFailed = !verifyChecksum(bytes[bytes.Length - 1]);
        }

        
        public bool verifyChecksum(byte cs)
        {
            return ((byte)(getMessageSum() + cs) == 0xFF);
        }
    }
}
